package com.ynet.middleground.approve.listener;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import com.ynet.core.exception.BusinessException;
import com.ynet.core.log.IfpLogger;
import com.ynet.middleground.approve.cmd.SpringContextUtils;
import com.ynet.middleground.approve.constant.OperatingTypeEnum;
import com.ynet.middleground.approve.constant.VotingVariables;
import com.ynet.middleground.approve.constant.WorkflowConstants;

/**
 * @author liulx
 * @description 会签任务完成时监听
 * @date 2019-11-25 00:24
 */
@Component
@DependsOn("springContextUtils")
public class CompleteMultiTaskListener implements TaskListener, VotingVariables {

    private RuntimeService runtimeService = SpringContextUtils.getBean(RuntimeService.class);
    private TaskService taskService = SpringContextUtils.getBean(TaskService.class);

    @Override
    public void notify(DelegateTask delegateTask) {
        // 获取流程id
        String exId = delegateTask.getExecutionId();
        // String exId = delegateTask.getProcessInstanceId();
        /*
            获取流程参数 shortingSwitch, 短路开关，会签人员完成自己的审批任务时会
            添加流程参数 user_task_approve_result，4 为拒绝，1为同意
        */
        // 同意人数
        Object agreedInstances = runtimeService.getVariable(exId, NUMBER_OF_AGREED_INSTANCES);
        Integer agreedCount = 0;
        if (agreedInstances != null) {
            agreedCount = (Integer)agreedInstances;
        }

        // 不同意（拒绝）人数
        Object disagreedInstances = runtimeService.getVariable(exId, NUMBER_OF_DISAGREED_INSTANCES);
        Integer disagreedCount = 0;
        if (disagreedInstances != null) {
            disagreedCount = (Integer)disagreedInstances;
        }

        // 获取用户审批结果
        // Object userTaskApproveResult = runtimeService.getVariable(exId, WorkflowConstants.USER_TASK_APPROVE_RESULT);
        Object userTaskApproveResult = delegateTask.getVariableLocal(WorkflowConstants.USER_TASK_APPROVE_RESULT);
        // 会签用户审批投票结果, 默认投拒绝票
        Integer userTaskApproveResultCode = OperatingTypeEnum.REFUSE.getCode();
        if (userTaskApproveResult != null) {
            userTaskApproveResultCode = (Integer)userTaskApproveResult;
        }

        if (userTaskApproveResultCode == OperatingTypeEnum.PASS.getCode()) {
            // 如果用户投同意票, 同意人数变量值+1
            agreedCount++;
            runtimeService.setVariable(exId, NUMBER_OF_AGREED_INSTANCES, agreedCount);
        } else if (userTaskApproveResultCode == OperatingTypeEnum.REFUSE.getCode()) {
            // 如果用户投拒绝票, 不同意人数变量值+1
            disagreedCount++;
            runtimeService.setVariable(exId, NUMBER_OF_DISAGREED_INSTANCES, disagreedCount);
        } else {
            throw new BusinessException("会签任务审批参数值不正确", "ECAP0503");
        }
        /*
         * 4：有一个人拒绝，整个流程就结束了，
         * 	因为Complete condition的值为 exclusive_gateway_variable == 'fail'，即，当流程参数为pass时会签就结束开始下一个任务
         * 1：审批人同意，同时要判断是不是所有的人都已经完成了，而不是由一个人同意该会签就结束
         * 	值得注意的是如果一个审批人完成了审批进入到该监听时nrOfCompletedInstances的值还没有更新，因此需要+1
         */
        // 获取短路开关变量
        Object shortingSwitchvariable = runtimeService.getVariable(exId, SHORTING_SWITCH);
        boolean shortingSwitch = false;
        if (shortingSwitchvariable != null) {
            if (shortingSwitchvariable instanceof Boolean) {
                shortingSwitch = (Boolean)shortingSwitchvariable;
            } else {
                throw new BusinessException("shortingSwitch 变量值错误", "ECAP0502");
            }
        }
        /*Object exclusiveGatewayVariable =
            runtimeService.getVariable(exId, WorkflowConstants.EXCLUSIVE_GATEWAY_VARIABLE);
        if (exclusiveGatewayVariable == null) {
            runtimeService.setVariable(exId, WorkflowConstants.EXCLUSIVE_GATEWAY_VARIABLE,
                WorkflowConstants.USER_TASK_APPROVE_RESULT_PASS);
        }*/
        // 短路开关如果开启，则只要有1人投反对票，则网关变量 exclusive_gateway_variable 结果就为 fail
        if (shortingSwitch) {
            if (disagreedCount != 0) {
                // 会签结束，设置网关变量 为 fail
                runtimeService.setVariable(exId, WorkflowConstants.EXCLUSIVE_GATEWAY_VARIABLE,
                    WorkflowConstants.USER_TASK_APPROVE_RESULT_FAIL);
                taskService.setVariableLocal(delegateTask.getId(), WorkflowConstants.EXCLUSIVE_GATEWAY_VARIABLE,
                    WorkflowConstants.USER_TASK_APPROVE_RESULT_FAIL);
            } else {
                Integer complete = (Integer)runtimeService.getVariable(exId, NUMBER_OF_COMPLETED_INSTANCES);
                Integer all = (Integer)runtimeService.getVariable(exId, NUMBER_OF_INSTANCES);
                // 都完成了并且并且没有人拒绝
                if ((complete + 1) == all && agreedCount.equals(all)) {
                    runtimeService.setVariable(exId, WorkflowConstants.EXCLUSIVE_GATEWAY_VARIABLE,
                        WorkflowConstants.USER_TASK_APPROVE_RESULT_PASS);
                    taskService.setVariableLocal(delegateTask.getId(), WorkflowConstants.EXCLUSIVE_GATEWAY_VARIABLE,
                        WorkflowConstants.USER_TASK_APPROVE_RESULT_PASS);
                }
            }
        }
        // 记录每次会签实例任务处理后的同意人数、不同意人数
        taskService.setVariableLocal(delegateTask.getId(), NUMBER_OF_AGREED_INSTANCES, agreedCount);
        taskService.setVariableLocal(delegateTask.getId(), NUMBER_OF_DISAGREED_INSTANCES, disagreedCount);
        IfpLogger.info(Thread.currentThread().getStackTrace()[1].getMethodName(), "executionId:{} 完成会签操作：", exId);
    }

}
